package com.laoxu.java.thread;

/**
 * @Author laoxu
 * @Date 2022/11/23 10:20
 * @Desc 线程同步操作，模拟银行取钱
 */
public class ThreadSynchronized{
    public static void main(String[] args) {
        Account account = new Account(100,"结婚基金");
        Drawing you = new Drawing(account,50,"你");
        Drawing gf = new Drawing(account,100,"gf");
        you.start();
        gf.start();
    }
}

class Drawing extends Thread{
    private Account account;
    private int drawingMoney;
    private int nowMoney;

    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }
    @Override
    public void run() {
        synchronized (account){
            if(account.money-drawingMoney < 0){
                System.out.println("余额不足！"+Thread.currentThread().getName()+"无法取"+drawingMoney);
                return;
            }
            account.money -= drawingMoney;
            nowMoney += drawingMoney;

            System.out.println(account.name+"余额为："+account.money);
            System.out.println(this.getName()+"手里的钱："+nowMoney);
        }
    }
}

// 账户
class Account{
    int money;
    String name;

    public Account(int money,String name){
        this.money = money;
        this.name = name;
    }
}

